<template>
  <base-page-view class-name="tab-container check-container-page" :show-to-top="false">
    <!-- #ifdef MP-WEIXIN -->
    <!-- <base-nav title="确认订单">
      <view slot="left" class="header-left" @click="handelBack">
        <image src="/static/images/icon/icon_arror_left.png" />
      </view>
    </base-nav> -->
    <!-- #endif -->
    <view v-if="showMaskDialog" class="maskDialog"></view>
    <view id="wrapper" class="check-container">
      <view v-if="showTips && boxType !== 'take'" class="noDelivery deli-tip-box" @click="showMessage(boxType)">
        <image src="/static/images/icon/icon__tip_public.png" alt="" class="deli-ti-icon"></image>
        <text class="deli-tip">查看申购指南，了解如何操作</text>
        <view class="deli-btn" @click.stop.prevent="showTips = false">
          <image src="/static/images/icon/icon_top_close.png" class="deli-ti-icon"></image>
        </view>
      </view>
      <view v-if="boxType === 'apply' && applyData.approvalMobile" class="apply-data-box">
        <view class="apply-tips">请确认下方「审批人」与您线下支付货款的「审批人」为同一人</view>
        <view class="apply-parent-box">
          <view class="row">
            <view class="b-b">手机号</view>
            {{ applyData.approvalMobile || '无' }}
          </view>
          <view class="row">
            <view class="b-b">审批人昵称</view>
            {{ applyData.approvalNickname || '无' }}
          </view>
          <view v-if="false" class="row">
            <view class="b-b">审批人姓名</view>
            {{ applyData.approvalRealName || '无' }}
          </view>
        </view>
      </view>
      <view v-if="boxType === 'take'" class="consignee">
        <view v-if="noSupDeliveryNum >= 1 && goodsNums > 1 && noSupDeliveryNum !== goodsNums && !isBoxPackageOrder" class="noDelivery">
          <image src="/static/images/icon/msg.png" alt="" class="deli-ti-icon"></image>
          <text class="deli-tip">温馨提示：订单中有部分商品暂不支持配送</text>
          <!--<span class="deli-tip">{{goodsTempObj.data.unsupported_area}}</span>-->
          <text class="deli-btn" @click="handleRemoveGood">点击移除</text>
        </view>
        <view class="sLine padding32" @click="goAddressList">
          <view v-if="!receiptAddress.address_id" class="lCont">
            <!-- <image src="/static/images/icon/icon_address.png" class="address-icon"></image> -->
            <view class="address-tip">请填写收货地址</view>
          </view>
          <view v-else class="lCont addressBox">
            <image src="/static/images/inventory/localtion_icon.png" class="address-icon"></image>
            <view class="addressItem">
              <view class="editRow">
                <view>{{ receiptAddress.name }}</view>
                <view>{{ receiptAddress.region_code + ' ' + receiptAddress.mobile }}</view>
              </view>
              <view class="detail">{{ receiptAddress.province + receiptAddress.city + receiptAddress.area + receiptAddress.detail }}</view>
            </view>
          </view>
          <view class="rCont">
            <image src="/static/images/icon/icon_arror_right.png" class="right-icon"></image>
          </view>
        </view>
        <image v-if="!receiptAddress" src="/static/images/icon/Corrugatedline.png" style="width:100%;height: 9rpx;display:block;"></image>
      </view>
      <view class="product-all">
        <view v-if="goodsTempObj">
          <goods-item ref="goodsTempItem" :need-role="true" :shopping-items="goodsTempObj.data.shopping_items" :prevent-click="true" @cartNumChange="cartNumChange"></goods-item>
        </view>
        <view class="product-remark">
          <view class="o-span">买家留言</view>
          <input v-model="remark" class="o-input" placeholder-class="input-placeholder" type="text" placeholder="您对本次交易的说明" />
        </view>
        <!-- <view class="sLine tax-item" @click="handleShowTax">
          <view class="lCont">发票选择</view>
          <view v-if="enable" class="rCont">
            <text v-if="taxInfo.invoiceContent === '不开发票'" class="tax-type-txt">{{ taxInfo.invoiceContent }}</text>
            <text v-else class="tax-type-txt">{{ taxInfo.invoiceContent }}-{{ taxInfo.invoiceTitleType }}</text>
            <image class="tax-arr-ico" src="/static/images/icon/icon_arror_right_grey.png"></image>
          </view>
          <view v-else class="rCont">暂不支持开发票,如有疑问，联系客服</view>
        </view> -->
      </view>
      <view class="order-params">
        <view class="money-item">
          <view>
            <text class="money">商品总额</text>
            <image v-if="boxType === 'apply'" class="question-icon" src="/static/images/inventory/question_icon.png" mode="aspectFit" @click="showMessage('take')" />
          </view>
          <view>
            <text v-if="boxType === 'buy'" class="money">￥{{ totalPrice | formatMoney }}</text>
            <text v-else-if="boxType === 'apply'" class="money line-through">￥{{ goodsPrice | formatMoney }}</text>
            <text v-else class="money ">￥{{ goodsPrice | formatMoney }}</text>
          </view>
        </view>
        <view class="money-item">
          <view>
            <text class="money">运费</text>
          </view>
          <view>
            <text v-if="boxType !== 'take'" class="money">提货时，按实际发生的运费进行收取</text>
            <text v-else class="money">￥{{ goodsTempObj.data.express_fee | formatMoney }}</text>
          </view>
        </view>
        <view v-if="boxType === 'take'" class="money-item">
          <view>
            <text class="money">实际付款</text>
          </view>
          <view>
            <text class="money">￥{{ totalPrice | formatMoney }}</text>
          </view>
        </view>
      </view>
      <!-- <view class="price-all">
        <view class="discount discount2">
          <view class="sLine">
            <view class="lCont">
              <text class="o-span">现金红包</text>
            </view>
            <view v-if="redPacketList.length" class="rCont" @click="showMask('redPacket')">
              <text v-if="selectedPacket.price" class="color-price">￥{{ selectedPacket.price | formatMoney }}</text>
              <text v-else class="packet-num-show">
                {{ redPacketList.length }}个可用
              </text>
              <image src="/static/images/icon/icon_arror_right_grey.png" />
            </view>
            <view v-else class="rCont" @click="showMask('redPacket')">
              <text class="packet-num-show disable">
                0个可用
              </text>
            </view>
          </view>
        </view>
      </view> -->
      <!-- <view class="price-all">
        <view class="discount">
          <view class="sLine">
            <view class="lCont">
              <text class="o-span">优惠券</text>
            </view>
            <view v-if="couponList.length > 0" class="rCont" @click="showMask('coupon')">
              <text v-if="selectedCoupon.price" class="color-price">立减{{ selectedCoupon.price | formatMoney }}元</text>
              <text v-else class="packet-num-show">
                {{ couponList.length }}个可用
              </text>
              <image src="/static/images/icon/icon_arror_right_grey.png" />
            </view>
            <view v-else class="rCont" @click="showMask('coupon')">
              <text class="packet-num-show disable">
                0个可用
              </text>
            </view>
          </view>
        </view>
        <view class="price-detail">
          <view class="sLine">
            <view class="lCont">
              <text class="o-span">商品金额：</text>
            </view>
            <view class="rCont">
              <text v-if="goodsTempObj && goodsTempObj.data" class="o-span">¥{{ goodsTempObj.data.goods_total | formatMoney }}</text>
            </view>
          </view>
          <view class="sLine">
            <view class="lCont">
              <text class="o-span">促销活动：</text>
            </view>
            <view class="rCont">
              <text v-if="goodsTempObj && goodsTempObj.data" class="o-span">-¥{{ goodsTempObj.data.discount_activity | formatMoney }}</text>
            </view>
          </view>
          <view v-if="selectedPacket" class="sLine">
            <view class="lCont">
              <text class="o-span">红包减免：</text>
            </view>
            <view class="rCont">
              <text v-if="selectedPacket && selectedPacket.price" class="o-span">-¥{{ selectedPacket.price | formatMoney }}</text>
              <text v-else class="o-span">-¥0.00</text>
            </view>
          </view>
          <view class="sLine">
            <view class="lCont">
              <text class="o-span">优惠减券：</text>
            </view>
            <view class="rCont">
              <text v-if="selectedCoupon && selectedCoupon.price" class="o-span">-¥{{ selectedCoupon.price | formatMoney }}</text>
              <text v-else class="o-span">-¥0.00</text>
            </view>
          </view>
          <view class="sLine">
            <view class="lCont">
              <text class="o-span">会员立减：</text>
            </view>
            <view class="rCont">
              <text v-if="goodsTempObj && goodsTempObj.data" class="o-span">-¥{{ goodsTempObj.data.discount_member | formatMoney }}</text>
            </view>
          </view>
          <view class="sLine">
            <view class="lCont">
              <text class="o-span">活动立减：</text>
            </view>
            <view class="rCont">
              <text v-if="goodsTempObj && goodsTempObj.data" class="o-span">-¥{{ goodsTempObj.data.discount_promotion | formatMoney }}</text>
            </view>
          </view>
          <view class="sLine">
            <view class="lCont">
              <text class="o-span">邮费：</text>
            </view>
            <view class="rCont">
              <text v-if="goodsTempObj && goodsTempObj.data && goodsTempObj.data.express_fee" class="o-span">¥{{ goodsTempObj.data.express_fee | formatMoney }}</text>
              <text v-else class="o-span">包邮</text>
            </view>
          </view>
          <view class="sLine">
            <view class="lCont">
              <text class="o-span">合计：</text>
            </view>
            <view class="rCont">
              <text v-if="goodsTempObj&&goodsTempObj.data" class="o-span">¥{{ goodsTempObj.data.total | formatMoney }}</text>
            </view>
          </view>
        </view>
      </view> -->
      <view class="pic-bottomFix">
        <view v-if="boxType === 'buy'" class="boxPayTips">
          支付成功后，商品将放入您的云仓仓库中。快去找人发起申购吧
        </view>
        <view v-if="boxType === 'apply'" class="bottom-container">
          <view class="rButton aButton" :class="{ disable: !applyData.approvalMobile }" @click="stockApply">提交({{ goodsNums }}箱)</view>
        </view>
        <view v-else class="bottom-container">
          <view class="lPrice">
            <text class="o-span">合计:￥</text>
            <text class="o-b">{{ totalPrice | formatMoney }}</text>
          </view>
          <view v-if="noSupDeliveryNum == 0" class="rButton" :class="{ disable: soldOutList }" @click="showPay()">
            {{ boxType === 'buy' ? '去付款' : '去付运费' }}
          </view>
          <!-- 单个商品 -->
          <view v-if="(noSupDeliveryNum == 1 && goodsNums <= 1) || noSupDeliveryNum === goodsNums" class="rButton" style="flex: 0 0 auto;padding:0 10px;background:#B9B9C8;">
            该地区暂不支持配送
          </view>
          <view v-else-if="noSupDeliveryNum >= 1 && goodsNums > 1" class="rButton" style="flex: 0 0 auto;padding:0 10px;background:#B9B9C8;">
            有商品不支持配送
          </view>
        </view>
      </view>
    </view>
    <pay-dialog ref="payDialog" :order-no="order_no" :form-type="getType" @submitCallBack="toPayResult" @close="close"></pay-dialog>
    <couponCom :show="showCoup" :coupon-list="couponList" :unusable-coupon-list="unusable_coupon_list" :selected-coupon="selectedCoupon" @close="handleSelected" @selectCoup="handleSelected" />
    <redPacketCom :show="showPacket" :red-packet-list="redPacketList" :selected-packet="selectedPacket" @close="handleSelected" @selectPacket="handleSelected" />
    <tax-com :show="showTax" :tax-info="taxInfo" @close="showTax = false" @deliver="getTaxData" />
    <confirm-popup ref="confirm" />
    <confirm-popup ref="groupBuyConfirm" />
    <guide v-if="boxType === 'buy' || boxType === 'apply'" position="top: 100rpx; width:600rpx" :guide-pic="`/static/images/box/box_guide_${boxType}.png`"></guide>
    <modal ref="ruleModal" :title="ruleData.title" :content="ruleData.content" :content-list="ruleData.contentList" />
  </base-page-view>
</template>

<script>
import './index.scss'
import { mapGetters, mapActions } from 'vuex'
import { getUserLevel } from '@/utils/common'
import Guide from '@/components/guide/index'
import payDialog from '../components/payDialog'
import couponCom from '../components/couponCom'
import redPacketCom from '../components/redPacketCom'
import taxCom from '../components/taxCom'
import goodsItem from '../components/goodsItem'
import confirmPopup from '@/components/confirmPopup/index'
import { formatUrlParam, debounce } from '@/utils/tools'
import modal from '../components/modal/index'
import { navigateToMiniProgram, toMpHomePage, pageNavigateBack } from '@/utils/navigateTo'

const RULE_OBJ = {
  take: {
    title: '提示',
    content: '线下支付'
  },
  buy: {
    title: '申购指南',
    contentList: ['当您向平台支付货款后，平台将划拨商品库存到您的云仓中', '通知您的团队成员发起申购', '待您审批通过后，将自动扣减您的库存，划拨给您的申购人']
  },
  apply: {
    title: '申购指南',
    contentList: ['与“审批人”确认申购的商品和数量，并线下支付货款', '进入审批环节，审批人通过后，即可调拨商品到您的云仓仓库', '提货时，请填写收货地址; 待支付运费后，即可发货到您指定的地址']
  }
}
let tempShipping = '[]'
export default {
  components: {
    goodsItem,
    payDialog,
    couponCom,
    redPacketCom,
    confirmPopup,
    taxCom,
    modal,
    Guide
  },
  data() {
    return {
      showTips: true,
      boxType: '',
      cartNum: 0,
      soldOutList: false,
      isBoxPackageOrder: false,
      receiptAddress: {}, // 接收的地址
      remark: '', // 评论
      applyData: {},
      coupontitle: '可使用优惠券',
      couponList: [], // 优惠券列表
      unusable_coupon_list: [], // 不可使用的优惠券
      redPacketList: [], // 红包列表
      selectedCoupon: {}, // 选择的优惠券
      selectedPacket: {}, // 选择的红包
      activity_id: '',
      address_id: '', // 选择的地址id
      order_no: '',
      invite_code: '',
      showCoup: false, // 显示优惠券
      showPacket: false, // 显示红包
      is_used_coupon: 0, // 是否使用优惠券
      showTax: false, // 显示发票
      preseat: '',
      firstseat: '',
      isFirst: true,
      showMaskDialog: false,
      enable: true, // 全国发票配置开关
      taxInfo: {},
      ruleData: {
        title: '',
        content: ''
      }
    }
  },
  computed: {
    ...mapGetters([
      'goodsTempObj',
      'userToken',
      'extraData',
      'user'
      // 'prePageTitle',
      // 'preSeat'
    ]),
    goodsNums() {
      if (!this.goodsTempObj) return 0
      let num
      if (this.boxType === 'take') {
        num = this.goodsTempObj.data.shopping_items.item_list.length + this.goodsTempObj.data.shopping_items.activity_item_list.length
      } else {
        num = this.cartNum || this.goodsTempObj.data.shopping_items.item_list[0].num
      }
      return num
    },
    // 配送地区判断
    noSupDeliveryNum() {
      if (!this.goodsTempObj) return 0
      let flag = 0
      this.goodsTempObj.data.shopping_items.item_list.forEach(item => {
        if (!item.is_sup_delivery) {
          flag += 1
        }
      })
      this.goodsTempObj.data.shopping_items.activity_item_list.forEach(item => {
        if (!item.is_sup_delivery) {
          flag += 1
        }
      })
      return flag
    },
    totalPrice() {
      if (!this.goodsTempObj) return 0
      return this.goodsTempObj.data.total
    },
    goodsPrice() {
      if (!this.goodsTempObj) return 0
      if (this.boxType === 'apply') {
        const gitem = this.goodsTempObj.data.shopping_items.item_list[0]
        return this.cartNum * gitem.vip_price || gitem.num * gitem.vip_price
      }
      return this.goodsTempObj.data.goods_total
    }
  },
  onLoad(options) {
    if (!this.userToken) {
      this.$navigateTo('/pages/login/index')
      return
    }
    this.query = {
      ...options
    }
    switch (this.query.boxType) {
      case 'buy':
        this.boxType = 'buy'
        uni.setNavigationBarTitle({
          title: '确认申购'
        })
        break
      case 'apply':
        this.boxType = 'apply'
        uni.setNavigationBarTitle({
          title: '确认申购'
        })
        this.getParentMsg()
        break
      case 'take':
        this.boxType = 'take'
        break
      default:
        this.boxType = 'take'
        break
    }
    this.isFirst = true
    if (!this.goodsTempObj) {
      if (this.extraData && this.extraData.platform) {
        toMpHomePage()
      } else {
        // #ifdef H5
        history.back()
        // #endif
        // #ifndef H5
        uni.navigateBack()
        return
        // #endif
      }
    }
  },
  onShow() {
    if (!this.goodsTempObj) {
      return
    }
    if (this.isFirst && this.boxType !== 'apply') {
      this.couponList = JSON.parse(JSON.stringify(this.goodsTempObj.data.coupon_list))
      this.unusable_coupon_list = JSON.parse(JSON.stringify(this.goodsTempObj.data.unusable_coupon_list))
      this.redPacketList = JSON.parse(JSON.stringify(this.goodsTempObj.data.hongbao_list))
      this.isFirst = false
    }

    console.log(this.goodsTempObj)
    tempShipping = this.goodsTempObj.shopping_list
    // 清除非正常操作可能存在拼团的缓存
    uni.removeStorageSync('_group_item_info_')
    // 缓存信息给拼团用
    if (Number(JSON.parse(this.goodsTempObj.shopping_list)[0].from_type) === 25) {
      const itemInfo = this.goodsTempObj
      uni.setStorageSync('_group_item_info_', JSON.stringify(itemInfo))
    }
    const invite_code = uni.getStorageSync('share_code')
    console.log('invite_code', invite_code)
    if (invite_code) {
      this.invite_code = invite_code
    }
    // 获取选择地址回来的地址
    if (this.addressData) {
      this.address_id = this.addressData.address_id
    }

    // 评价内容
    const remark = uni.getStorageSync('__tempRemark__')

    if (remark) {
      this.remark = remark
      uni.setStorageSync('__tempRemark__', '')
    } else {
      this.remark = ''
    }

    if (this.goodsTempObj.data.coupon_list.length) {
      this.is_used_coupon = 1
      this.selectedCoupon = this.goodsTempObj.data.coupon ? this.goodsTempObj.data.coupon : {}
    } else {
      this.is_used_coupon = 0
    }
    if (this.goodsTempObj.data.hongbao_list.length) {
      this.selectedPacket = this.goodsTempObj.data.hongbao ? this.goodsTempObj.data.hongbao : {}
    }
    this.preseat = uni.getStorageSync('preseat') ? uni.getStorageSync('preseat') : ''
    this.firstseat = uni.getStorageSync('firstseat') ? uni.getStorageSync('firstseat') : ''
    if (this.boxType === 'take') {
      this._getAddress()
    }

    this.getInvoiceSetting()
  },
  methods: {
    ...mapActions(['setGoodsTemp']),
    getType() {
      return Number(JSON.parse(this.goodsTempObj.shopping_list)[0].from_type)
    },
    // 问号提示
    showMessage(type) {
      this.ruleData = RULE_OBJ[type]
      this.$refs.ruleModal.show()
    },
    // 添加订单
    async addOrder(type) {
      if (this.soldOutList) {
        return
      }
      if (this.extraData && this.extraData.data && this.extraData.data.event_liks) {
        this.$trackSDK.EVENT_LINKS = this.extraData.data.event_liks
      }
      const data = {
        preseat: this.preseat, // 页面
        firstseat: this.$trackSDK.EVENT_LINKS ? this.$trackSDK.EVENT_LINKS : this.firstseat, // 模块
        shopping_list: this.goodsTempObj.shopping_list,
        shipping_address_id: this.receiptAddress.address_id || '',
        remark: this.remark,
        coupon_id: this.selectedCoupon.coupon_id ? this.selectedCoupon.coupon_id : '',
        hongbao_id: this.selectedPacket.hongbao_id ? this.selectedPacket.hongbao_id : '',
        activity_id: this.activity_id
      }
      if (this.boxType !== 'apply') {
        // 2为下单权限
        if (this.boxType === 'buy') {
          data.new_box_order_type = 1
        } else {
          data.new_box_order_type = 2
        }
        if (this.goodsTempObj.settleData) {
          data.stock_goods_id = this.goodsTempObj.settleData.stock_goods_id
          data.stock_sku_code = this.goodsTempObj.settleData.stock_sku_code
        }
      }
      // 如果有邀请码，则将邀请码一起写进去
      if (this.invite_code) {
        data.inviteCode = this.invite_code
      }
      console.log('addOrder', data)
      const res = await this.$api.orderApi.orderAdd(data)
      // 5000 为拼团名额已满
      if (res.code === 5000) {
        uni.showToast({
          title: res.msg || res.message,
          icon: 'none',
          duration: 2000,
          mask: true
        })
        const groupId = JSON.parse(this.goodsTempObj.shopping_list)[0].group_id
        // 这边需要跳转
        const query = {
          group_id: groupId,
          group_full: true
        }
        const url = formatUrlParam('/pagesActivity/group-buy/result', query)
        this.$navigateTo(url)
        return
      }
      if (res.code) {
        if (res.code === 201 && res.data) {
          if (res.data && res.data.skuCodeList.length > 0) {
            this.soldOutList = true
          }
          const goodsTemp = JSON.parse(JSON.stringify(this.goodsTempObj))
          const shopItem = goodsTemp.data.shopping_items
          if (shopItem.activity_item_list.length > 0) {
            shopItem.activity_item_list.forEach(item => {
              if (res.data.skuCodeList && res.data.skuCodeList.indexOf(item.sku_code) >= 0) {
                item.soldOut = true
              }
              // 如果有套餐内容
              if (item.pack) {
                const packList = item.pack.pack_list
                const presentList = item.pack.present_list
                if (packList.length) {
                  packList.forEach(i => {
                    if (res.data.skuCodeList.indexOf(i.sku_code) >= 0) {
                      i.soldOut = true
                    }
                  })
                }
                if (presentList.length) {
                  presentList.forEach(i => {
                    if (res.data.skuCodeList.indexOf(i.sku_code) >= 0) {
                      i.soldOut = true
                    }
                  })
                }
              }
            })
          }
          // 下单售罄
          if (shopItem.item_list.length > 0) {
            shopItem.item_list.forEach(item => {
              if (res.data.skuCodeList.indexOf(item.sku_code) >= 0) {
                item.soldOut = true
              }
              if (item.pack) {
                const packList = item.pack.pack_list
                const presentList = item.pack.present_list
                if (packList.length) {
                  packList.forEach(i => {
                    if (res.data.skuCodeList.indexOf(i.sku_code) >= 0) {
                      i.soldOut = true
                    }
                  })
                }
                if (presentList.length) {
                  presentList.forEach(i => {
                    if (res.data.skuCodeList.indexOf(i.sku_code) >= 0) {
                      i.soldOut = true
                    }
                  })
                }
              }
            })
          }
          this.$nextTick(() => {
            this.setGoodsTemp({
              shopping_list: goodsTemp.shopping_list,
              data: goodsTemp.data
            })
          })
        }
        return false
      }
      this.order_no = res.data.order_no
      if (this.extraData && this.extraData.data && this.extraData.data.fromSource === 'shoppingBag' && this.extraData.data.liveId && this.extraData.data.shopping_list) {
        // 删除直播购物袋的接口
        const skuList = []
        const shopping_list = JSON.parse(this.extraData.data.shopping_list)
        shopping_list.forEach(item => {
          skuList.push(item.sku_code)
        })
        if (skuList.length > 0) {
          await this.$api.orderApi.delLiveBag({
            liveId: this.extraData.data.liveId,
            skuListStr: skuList.join(',')
          })
        }
      }
      // this.$store.dispatch('setPreSeat', '')
      return true
    },
    // 去支付
    async showPay() {
      // if (!this.receiptAddress || !this.receiptAddress.address_id) {
      //   this.$gc.$message({
      //     content: '您还没有收货地址，请点击添加',
      //     title: '提示',
      //     showMessage: true,
      //     confirmText: '添加',
      //     align: 'center',
      //     confirm: async() => {
      //       this.$navigateTo('/pagesMine/address/address')
      //     }
      //   })
      //   return
      // }
      // if (!/^\d{1,11}$/.test(this.receiptAddress.mobile)) {
      //   uni.showToast({
      //     title: '亲，您的收货手机号不是纯数字滴，请修改呦！',
      //     icon: 'none',
      //     duration: 2000,
      //     mask: true
      //   })
      //   return
      // }
      if (this.taxInfo.invoiceContent !== '不开发票') {
        let msg = ''
        if (!this.taxInfo.email.trim()) {
          msg = '发票信息邮箱不能为空'
        }
        if (!this.taxInfo.invoiceTitle.trim()) {
          msg = this.taxInfo.invoiceTitleType === '单位' ? '发票信息单位名称不能为空 ' : '发票信息姓名不能为空'
        }
        if (this.taxInfo.invoiceTitleType === '单位' && !this.taxInfo.gmfTaxpayerIdentifyNo.trim()) {
          msg = '发票信息纳税人识别号不能为空'
        }
        const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if (!reg.test(this.taxInfo.email.trim())) {
          msg = '发票信息邮箱地址格式不正确'
        }
        if (msg) {
          uni.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          })
          return
        }
      }
      if (this.showPaying) return
      this.showPaying = true
      if (!this.order_no) {
        if (!(await this.addOrder())) {
          this.showPaying = false
          return
        }
      }

      if (this.taxInfo.invoiceContent !== '不开发票') {
        const shopping_list = JSON.parse(this.goodsTempObj.shopping_list)
        const isBox = shopping_list.findIndex(i => i.from_type * 1 === 11)
        this.taxInfo.orderNo = this.order_no
        this.taxInfo.orderType = isBox > -1 ? 11 : ''
        this.taxInfo.userId = this.user.uid
        // 申请发票
        await this.$api.invoiceApi.applyInvoice(this.taxInfo)
      }

      this.$refs.payDialog.show()
      this.showPaying = false
    },
    // 支付结果
    toPayResult(data) {
      // #ifdef H5
      const type = data.type
      if (type === '2') {
        // h5支付
        let wechatUrl = data.url
        const fromType = Number(JSON.parse(this.goodsTempObj.shopping_list)[0].from_type)
        if (fromType === 25) {
          // 如果是参团
          if (JSON.parse(this.goodsTempObj.shopping_list)[0].group_id) {
            wechatUrl += `&redirect_url=${encodeURIComponent(
              location.origin + '/pagesActivity/group-buy/result?group_id=' + Number(JSON.parse(this.goodsTempObj.shopping_list)[0].group_id) + '&order_no=' + this.order_no
            )}`
          } else {
            // 开团
            wechatUrl += `&redirect_url=${encodeURIComponent(location.origin + '/pagesActivity/group-buy/result?group_id=&order_no=' + this.order_no)}`
          }
        } else {
          wechatUrl += `&redirect_url=${encodeURIComponent(location.origin + '/pagesOrder/orderSuccess/index?orderNo=' + this.order_no)}`
        }
        location.href = wechatUrl
      } else if (type === '3') {
        let wechatUrl = ''
        const fromType = Number(JSON.parse(this.goodsTempObj.shopping_list)[0].from_type)
        uni.setStorageSync('__success_return__', {
          url: location.href,
          orderNo: this.order_no
        })
        if (fromType === 25) {
          // 如果是参团
          if (JSON.parse(this.goodsTempObj.shopping_list)[0].group_id) {
            wechatUrl = `${encodeURIComponent(location.origin + '/pagesActivity/group-buy/result?group_id=' + Number(JSON.parse(this.goodsTempObj.shopping_list)[0].group_id))}`
          } else {
            // 开团
            wechatUrl = `${encodeURIComponent(location.origin + '/pagesActivity/group-buy/result?group_id=&order_no=' + this.order_no)}`
          }
          // 公众号支付
          this.$api.orderApi.orderPayWechat({
            order_no: this.order_no,
            wechatUrl // 回调地址
          })
        } else {
          wechatUrl = `${encodeURIComponent(location.origin + '/pagesOrder/orderSuccess/H5ResultGet?orderNo=' + this.order_no)}`
        }
      }
      // #endif

      // #ifdef MP-WEIXIN
      const fromType = Number(JSON.parse(this.goodsTempObj.shopping_list)[0].from_type)
      // 拼单的转跳
      if (fromType === 25) {
        let miniUrl = ''
        if (JSON.parse(this.goodsTempObj.shopping_list)[0].group_id) {
          // 参团
          miniUrl = '/pagesActivity/group-buy/result?group_id=' + Number(JSON.parse(this.goodsTempObj.shopping_list)[0].group_id)
        } else {
          // 开团
          miniUrl = '/pagesActivity/group-buy/result?group_id=&order_no=' + this.order_no
        }
        this.$store.dispatch('setGoodsTemp', null)
        this.$navigateTo(miniUrl, '', 'redirectTo')
      } else {
        this.$store.dispatch('setGoodsTemp', null)
        this.$navigateTo(`/pagesOrder/orderSuccess/index?id=${this.order_no}&boxType=${this.boxType}`, '', 'redirectTo')
      }
      // #endif
    },
    // 未支付跳转到订单详情
    close() {
      this.$navigateTo(`/pagesBox/pick-up-detail/index?orderNo=${this.order_no}&boxType=${this.boxType}`, '', 'redirectTo')
    },
    // 点击移除商品
    handleRemoveGood() {
      this.$refs.confirm.show({
        title: '提示',
        content: '订单中有' + this.noSupDeliveryNum + '件商品暂不支持配送，确认删除才能正常下单',
        yesCb: () => {
          this.removeNoSupShop()
        }
      })
    },
    async stockApply() {
      if (!this.applyData.approvalMobile) {
        return
      }
      const goods = this.goodsTempObj.data.shopping_items.item_list[0] || {}
      const applyData = {
        ...this.applyData,
        applyRemark: this.remark,
        box_apply_goods_dtos_json: JSON.stringify([
          {
            goodsId: goods.goods_id,
            goodsName: goods.title,
            goodsNumber: this.cartNum || goods.num,
            goodsPrice: goods.vip_price,
            goodsSku: goods.sku_code,
            image: goods.pic,
            stockNumber: goods.stock_number
          }
        ]),
        goodsTotalAmt: this.goodsPrice,
        payTotalAmt: this.goodsPrice,
        postage: 0
      }
      const res = await this.$api.boxApi.stockApply(applyData)
      if (res.success) {
        // uni.showToast({
        //   title: '提交成功',
        //   icon: 'none',
        //   duration: 2000,
        //   mask: true
        // })
        this.$navigateTo(`/pagesOrder/orderSuccess/index?id=${res.data.id}&boxType=apply`, '', 'redirectTo')
        // this.$navigateTo(`/pagesBox/approval/detail?id=${res.data.id}&type=purchase`, {}, 'redirectTo')
      }
      console.log('res', res)
    },
    // 确定移除不支持配送的
    async removeNoSupShop() {
      const newList = this.goodsTempObj.data.shopping_items.item_list.filter(item => item.is_sup_delivery)
      const AnewList = this.goodsTempObj.data.shopping_items.activity_item_list.filter(item => item.is_sup_delivery)

      const res = {
        item_list: newList,
        activity_item_list: AnewList
      }
      // 做了移除以后的数量小于0 则直接返回上一页
      if (newList.length + AnewList.length <= 0) {
        this.handelBack()
        return
      }
      // 重新设置vuex的换乘

      const newGoodsTempObj = JSON.parse(JSON.stringify(this.goodsTempObj))
      newGoodsTempObj.data.shopping_items = res
      this.setGoodsTemp(newGoodsTempObj)

      const idList = []
      newList.forEach(item => {
        if (item.goods_id) {
          idList.push(item.goods_id)
        } else {
          idList.push(item.package_id)
        }
      })
      AnewList.forEach(item => {
        if (item.goods_id) {
          idList.push(item.goods_id)
        } else {
          idList.push(item.package_id)
        }
      })

      const shoppingListNew = []
      JSON.parse(this.goodsTempObj.shopping_list).map(item => {
        idList.map(i => {
          if (item.goods_id.indexOf(i) >= 0) {
            shoppingListNew.push(item)
          }
        })
      })
      const settleRes = await this.$api.orderApi.orderSettle({
        // is_used_coupon: this.couponList.length ? 1 : 0,
        coupon_id: this.selectedCoupon && this.selectedCoupon.coupon_id ? this.selectedCoupon.coupon_id : '',
        hongbao_id: this.selectedPacket && this.selectedPacket.hongbao_id ? this.selectedPacket.hongbao_id : '',
        is_used_coupon: this.is_used_coupon,
        shopping_list: JSON.stringify(shoppingListNew),
        shipping_address_id: this.receiptAddress.address_id
      })
      // 重新设置商品
      this.setGoodsTemp({
        shopping_list: JSON.stringify(shoppingListNew),
        data: settleRes.data
      })
    },
    // 显示弹窗
    showMask(type, limit) {
      switch (type) {
        case 'coupon':
          if (this.couponList.length > 0) {
            this.showCoup = true
          }

          break
        case 'redPacket':
          if (this.redPacketList.length > 0) {
            this.showPacket = true
          }
          break
        default:
          break
      }
    },
    // 红包，优惠券弹窗回调
    async handleSelected(data) {
      if (data.isClose) {
        this.showCoup = false
        this.showPacket = false
        return
      }
      const item = data.item
      if (data.type === 'redPacket') {
        this.selectedPacket = item
      } else if (data.type === 'coupon') {
        this.selectedCoupon = item
        this.is_used_coupon = this.selectedCoupon && this.selectedCoupon.coupon_id && data.type === 'coupon' ? 1 : 0
      }
      if (data.type) {
        this.reSettle()
      }
      this.showCoup = false
      this.showPacket = false
    },
    // 重新结算
    async reSettle(changeCoupon) {
      const newData = {
        is_used_coupon: Number(changeCoupon) || this.is_used_coupon,
        coupon_id: this.selectedCoupon && this.selectedCoupon.coupon_id && !changeCoupon ? this.selectedCoupon.coupon_id : '',
        hongbao_id: this.selectedPacket && this.selectedPacket.hongbao_id ? this.selectedPacket.hongbao_id : '',
        shipping_address_id: this.receiptAddress && this.receiptAddress.address_id ? this.receiptAddress.address_id : '',
        shopping_list: this.goodsTempObj.shopping_list,
        new_box_order_type: this.goodsTempObj.settleData ? this.goodsTempObj.settleData.new_box_order_type : '',
        stock_goods_id: this.goodsTempObj.settleData ? this.goodsTempObj.settleData.stock_goods_id : '',
        stock_sku_code: this.goodsTempObj.settleData ? this.goodsTempObj.settleData.stock_sku_code : ''
      }
      const res = await this.$api.orderApi.orderSettle(newData)
      if (res.success) {
        this.setGoodsTemp({
          shopping_list: this.goodsTempObj.shopping_list,
          data: res.data,
          settleData: newData
        })
        if (changeCoupon) {
          this.couponList = JSON.parse(JSON.stringify(this.goodsTempObj.data.coupon_list))
          this.unusable_coupon_list = JSON.parse(JSON.stringify(this.goodsTempObj.data.unusable_coupon_list))
          this.selectedCoupon = this.goodsTempObj.data.coupon ? this.goodsTempObj.data.coupon : {}
        }
      } else {
        // const tempList = JSON.parse(tempShipping)
        // console.log('old 8888:', tempList)
        // tempList.map(item => {
        //   const index = this.goodsTempObj.data.shopping_items.item_list.findIndex(i => i.goods_id === item.goods_id)
        //   if (index > -1) {
        //     this.goodsTempObj.data.shopping_items.item_list[index].num = item.num
        //   }
        // })
        // this.setGoodsTemp({
        //   shopping_list: this.goodsTempObj.shopping_list,
        //   data: this.goodsTempObj.data,
        //   settleData: newData
        // })
        // this.$forceUpdate()
        this.$refs.goodsTempItem && this.$refs.goodsTempItem.updateView(tempShipping)
        // console.log('this.$refs.goodsTempItem', this.$refs.updateView)
      }
      setTimeout(() => {
        this.showMaskDialog = false
      }, 500)
    },
    async getParentMsg() {
      const res = await this.$api.boxApi.getParentMsg()
      if (res.success) {
        this.applyData = {
          approvalMobile: res.data.mobile,
          approvalNickname: res.data.nickname,
          approvalRealName: res.data.real_name,
          approvalUserId: res.data.user_id
        }
        console.log('this.applyData', this.applyData)
      } else {
        setTimeout(() => {
          this.$gc.$message({
            content: '未查询到审批人, 请先线下确认审批人后再发起申购',
            title: '提示',
            showMessage: true,
            showCancel: false,
            confirmColor: '#fff',
            confirmBackground: '#000',
            confirmText: '我知道了',
            align: 'center',
            confirm: () => {},
            cancel: () => {}
          })
        }, 500)

        return
      }
    },
    // 获取地址
    async _getAddress() {
      if (!this.address_id) {
        const res = await this.$api.mineApi.getShippingAddressList()
        // 没有选中送货地址，但是查询列表有地址
        if (res.data && res.data.length > 0) {
          this.receiptAddress = this.goodsTempObj.data.shipping_address
        } else {
          this.receiptAddress = null
        }
        // 如果没有地址则弹窗提示添加
        if (!this.receiptAddress) {
          this.$refs.confirm.show({
            title: '提示',
            cancelTxt: '取消',
            yesTxt: '添加',
            content: '您还没有收货地址，请点击添加',
            yesCb: () => {
              this.goAddressList()
            }
          })
        }
        return
      }
      // 获取新地址以后，重新请求运费配送
      const res = await this.$api.mineApi.getShippingAddressList()
      res.data.forEach(element => {
        if (element.address_id === this.address_id) {
          this.receiptAddress = element
        }
      })
      // 重新设置数据
      this.reSettle()
    },
    // 订单数量修改
    cartNumChange: debounce(function(e) {
      if (this.boxType === 'apply') {
        this.cartNum = e.nums
        return
      }
      try {
        this.showMaskDialog = true
        const temp = JSON.parse(this.goodsTempObj.shopping_list)
        if (e.item.type === 2 && e.item.pack && e.item.pack.pack_list) {
          var packId = ''
          e.item.pack.pack_list.forEach(item => {
            packId += `_${item.sku_code}`
          })
        }
        temp.forEach(el => {
          if (e.item.type === 2) {
            let elPackId = ''
            el.pack_list.forEach(item => {
              elPackId += `_${item.sku_code}`
            })
            if (elPackId === packId) {
              el.num = e.nums
            }
          } else if (el.goods_id === e.item.goods_id && el.sku_code === e.item.sku_code) {
            this.tempItemNum = el.num
            el.num = e.nums
          }
        })
        this.goodsTempObj.shopping_list = JSON.stringify(temp)
      } catch (error) {
        console.log('cartNumChange error', error)
      }
      this.reSettle(true)
    }, 200),
    // 用户信息等级
    _getUserLevel(id) {
      return getUserLevel(id)
    },
    // 跳转到地址选项
    goAddressList() {
      uni.setStorageSync('__tempRemark__', this.remark)
      this.$navigateTo('/pagesMine/address/address?type=select')
    },
    // 返回
    handelBack() {
      if (this.extraData && this.extraData.platform) {
        navigateToMiniProgram({
          success: () => {
            toMpHomePage()
            console.log('返回成功')
            this.$store.dispatch('setExtraData', null)
            this.$store.dispatch('setGoodsTemp', null)
          }
        })
      } else {
        pageNavigateBack()
      }
    },
    // 获取发票配置开关
    async getInvoiceSetting() {
      const res = await this.$api.invoiceApi.getInvoiceSetting()
      if (res.success) {
        this.enable = res.data.enable
      }
    },
    // 显示发票弹窗
    handleShowTax() {
      if (this.enable) {
        this.showTax = true
      }
    },
    // 获取数据
    getTaxData(data) {
      this.taxInfo = data
    }
  },
  onBackPress(options) {
    if (options.from === 'navigateBack') {
      return false
    }
    if (!this.goodsTempObj) {
      uni.navigateBack()
      return
    }
    if (Number(JSON.parse(this.goodsTempObj.shopping_list)[0].from_type) === 25) {
      this.$refs.groupBuyConfirm.show({
        title: '确定要放弃付款吗',
        content: '你尚未完成支付，喜欢的商品 可能会被抢空哦~',
        yesCb: () => {
          uni.navigateBack()
        }
      })
    }
  }
}
</script>
